function globeImageryRedirect(app) {

    var request = require('request');
    var url = require('url');
    var CWebp = require('cwebp').CWebp;
    var DWebp = require('cwebp').DWebp;

    var baseKeyword = "GlobeImagery";
    var pattern = /(\d*)\/(\d*)\/(\d*)/;

    app.get("/" + baseKeyword + "/*", function (req, res, next) {

        var match = req.params[0].match(pattern);

        var x = match[1];
        var y = match[2];
        var z = match[3];

        var redirect = "https://mt.google.cn/maps/vt?lyrs=s@733&gl=en" +
            "&" +
            "x=" + x +
            "&" +
            "y=" + y + "" +
            "&" +
            "z=" + z;

        redirectMod();

        // proxyMod();


        function redirectMod() {
            res.redirect(302, redirect);
        }

        function proxyMod() {
            var dontProxyHeaderRegex = /^(?:Host|Proxy-Connection|Connection|Keep-Alive|Transfer-Encoding|TE|Trailer|Proxy-Authorization|Proxy-Authenticate|Upgrade)$/i;

            function filterHeaders(req, headers) {
                var result = {};
                // filter out headers that are listed in the regex above
                Object.keys(headers).forEach(function (name) {
                    if (!dontProxyHeaderRegex.test(name)) {
                        result[name] = headers[name];
                    }
                });
                return result;
            }

            function dealWebp() {
                // var encoder = new CWebp(body);

                // encoder.stream().then(function(stream) {
                //     console.log(stream);
                // });

                // encoder.toBuffer().then(function (buffer) {
                //     // response.body = buffer;
                //     console.log(buffer);
                // })

                // encoder.write('image.webp').then(function() {
                //     debugger;
                // });
            }

            request.get({
                url      : url.format(redirect),
                headers  : filterHeaders(req, req.headers),
                encoding : null
            }, function (error, response, body) {
                var code = 500;

                if (response) {
                    code = response.statusCode;
                    res.header(filterHeaders(req, response.headers));

                    if (code === 200 && response.headers["content-type"] == "image/jpeg") {
                        dealWebp();
                    }
                }

                res.status(code).send(body);
            });
        }


    });

}

module.exports = {globeImageryRedirect : globeImageryRedirect};